/**
 * 通用工具函数
 */

/**
 * 格式化时间
 */
export const formatTime = (time: string | Date, format: string = 'YYYY-MM-DD HH:mm:ss'): string => {
  if (!time) return ''
  
  const date = typeof time === 'string' ? new Date(time) : time
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', String(year))
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second)
}

/**
 * 格式化相对时间
 */
export const formatRelativeTime = (time: string | Date): string => {
  if (!time) return ''
  
  const date = typeof time === 'string' ? new Date(time) : time
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const month = 30 * day
  const year = 365 * day
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < month) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < year) {
    return `${Math.floor(diff / month)}个月前`
  } else {
    return `${Math.floor(diff / year)}年前`
  }
}

/**
 * 防抖函数
 */
export const debounce = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): T => {
  let timeout: NodeJS.Timeout | null = null
  
  return ((...args: Parameters<T>) => {
    if (timeout !== null) {
      clearTimeout(timeout)
    }
    
    timeout = setTimeout(() => {
      func(...args)
    }, wait)
  }) as T
}

/**
 * 节流函数
 */
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): T => {
  let lastCallTime = 0
  
  return ((...args: Parameters<T>) => {
    const now = Date.now()
    
    if (now - lastCallTime >= wait) {
      lastCallTime = now
      return func(...args)
    }
  }) as T
}

/**
 * 深拷贝
 */
export const deepClone = <T>(obj: T): T => {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime()) as any
  }
  
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item)) as any
  }
  
  if (typeof obj === 'object') {
    const copy: any = {}
    Object.keys(obj).forEach(key => {
      copy[key] = deepClone((obj as any)[key])
    })
    return copy
  }
  
  return obj
}

/**
 * 生成随机字符串
 */
export const randomString = (length: number = 8): string => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  
  return result
}

/**
 * 格式化文件大小
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
}

/**
 * 格式化数字
 */
export const formatNumber = (num: number, precision: number = 2): string => {
  if (num >= 1000000) {
    return `${(num / 1000000).toFixed(precision)}M`
  } else if (num >= 1000) {
    return `${(num / 1000).toFixed(precision)}K`
  }
  
  return num.toString()
}

/**
 * 验证手机号
 */
export const validatePhone = (phone: string): boolean => {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(phone)
}

/**
 * 验证邮箱
 */
export const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

/**
 * 获取设备状态显示文本
 */
export const getDeviceStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    fault: '故障',
    maintenance: '维护中'
  }
  
  return statusMap[status] || '未知'
}

/**
 * 获取设备状态颜色
 */
export const getDeviceStatusColor = (status: string): string => {
  const colorMap: Record<string, string> = {
    online: '#52C41A',
    offline: '#D9D9D9',
    fault: '#FF4D4F',
    maintenance: '#FAAD14'
  }
  
  return colorMap[status] || '#D9D9D9'
}

/**
 * 获取工单状态显示文本
 */
export const getWorkOrderStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    pending: '待处理',
    assigned: '已分配',
    in_progress: '进行中',
    on_hold: '暂停',
    completed: '已完成',
    cancelled: '已取消'
  }
  
  return statusMap[status] || '未知'
}

/**
 * 获取工单优先级显示文本
 */
export const getWorkOrderPriorityText = (priority: string): string => {
  const priorityMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  
  return priorityMap[priority] || '未知'
}

/**
 * 获取告警级别显示文本
 */
export const getAlertLevelText = (level: string): string => {
  const levelMap: Record<string, string> = {
    info: '信息',
    warning: '警告',
    error: '错误',
    critical: '严重'
  }
  
  return levelMap[level] || '未知'
}

/**
 * 获取告警级别颜色
 */
export const getAlertLevelColor = (level: string): string => {
  const colorMap: Record<string, string> = {
    info: '#1890FF',
    warning: '#FAAD14',
    error: '#FF4D4F',
    critical: '#722ED1'
  }
  
  return colorMap[level] || '#D9D9D9'
}

/**
 * 处理API错误
 */
export const handleApiError = (error: any): string => {
  if (error.message) {
    return error.message
  }
  
  if (error.errMsg) {
    return error.errMsg
  }
  
  return '操作失败，请稍后重试'
}